# plugs/reload.py
#
#

""" reload/unload commands """

__copyright__ = 'this file is in the public domain'

from gozerbot.config import config
from gozerbot.plugins import plugins
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.plughelp import plughelp
import os

plughelp.add('reload', 'reload a plugin')

def handle_reload(bot, ievent):
    """ reload <plugin> .. reload a plugin """
    try:
        plug = ievent.args[0].lower()
    except IndexError:
        ievent.missing('<plugin>')
        return
    if plug == 'config':
        config.reload()
        ievent.reply('config reloaded')
        return
    # first check myplugs then dbplugs and finally plugs dir
    got = 0
    if os.path.isfile('myplugs/%s.py' % plug):
        if plugins.reload('myplugs', plug):
            got = 1
    elif config['dbenable'] and os.path.isfile('dbplugs/%s.py' % plug):
        if not got and plugins.reload('dbplugs', plug):
            got = 1
    elif os.path.isfile('plugs/%s.py' % plug):
        if not got and plugins.reload('plugs', plug):
            got = 1
    if got:
        ievent.reply('%s reloaded' % plug)
    else:
        ievent.reply("error reloading %s plugin" % plug)

cmnds.add('reload', handle_reload, 'OPER')
examples.add('reload', 'reload <plugin>', 'reload core')

def handle_unload(bot, ievent):
    """ unload <plugin> .. unload a plugin """
    try:
        what = ievent.args[0].lower()
    except IndexError:
        ievent.missing('<plugin>')
        return
    if not plugins.exist(what):
        ievent.reply('there is no %s module' % what)
        return
    if plugins.unload(what):
        plugins.disable(what)
        ievent.reply("%s unloaded and disabled" % what)
    else:
        ievent.reply("%s unload failed" % what)

cmnds.add('unload', handle_unload, 'OPER')
examples.add('unload', 'unload <plugin>', 'unload test')
